#import "MessageSetTViewController.h"
#import "ZLAntiShakeSwitch.h"

@interface MessageSetTViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isFirstSwitchOn;
@property (nonatomic, assign) BOOL isSecondSwitchOn;
@property (nonatomic, assign) NSInteger selectedDisplayMode; // 0: 简洁, 1: 详细, 2: 智能折叠

@end

@implementation MessageSetTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"短信";
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    
    // 默认值设置
    self.isFirstSwitchOn = YES;
    self.isSecondSwitchOn = YES;
    self.selectedDisplayMode = 0;
    
    [self setupTableView];
    [self setupNavigationBar];
}

- (void)setupNavigationBar {
    // 添加重置防呆按钮
    UIBarButtonItem *resetButton = [[UIBarButtonItem alloc] initWithTitle:@"重置防呆" 
                                                                    style:UIBarButtonItemStylePlain 
                                                                   target:self 
                                                                   action:@selector(resetAntiShake)];
    self.navigationItem.rightBarButtonItem = resetButton;
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor systemGroupedBackgroundColor];
    [self.view addSubview:self.tableView];
}

#pragma mark - Custom Views

- (UIView *)createDisplayModeView {
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 140)];
    containerView.backgroundColor = [UIColor clearColor];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, containerView.bounds.size.width - 32, 30)];
    titleLabel.text = @"显示为";
    titleLabel.font = [UIFont systemFontOfSize:16];
    [containerView addSubview:titleLabel];
    
    // 创建水平滚动视图
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 30, containerView.bounds.size.width, 100)];
    scrollView.showsHorizontalScrollIndicator = NO;
    [containerView addSubview:scrollView];
    
    NSArray *titles = @[@"简洁", @"详细", @"智能折叠"];
    CGFloat cardWidth = 120;
    CGFloat cardHeight = 80;
    CGFloat cardSpacing = 12;
    CGFloat startX = 16;
    
    for (NSInteger i = 0; i < titles.count; i++) {
        UIView *cardView = [[UIView alloc] initWithFrame:CGRectMake(startX + i * (cardWidth + cardSpacing), 10, cardWidth, cardHeight)];
        cardView.layer.cornerRadius = 8;
        cardView.layer.borderWidth = 1;
        cardView.tag = i;
        
        // 设置卡片样式
        if (self.selectedDisplayMode == i) {
            cardView.backgroundColor = [[UIColor systemGreenColor] colorWithAlphaComponent:0.1];
            cardView.layer.borderColor = [UIColor systemGreenColor].CGColor;
        } else {
            cardView.backgroundColor = [UIColor systemBackgroundColor];
            cardView.layer.borderColor = [[UIColor systemGrayColor] colorWithAlphaComponent:0.2].CGColor;
        }
        
        // 预览图标
        UIView *previewBox = [[UIView alloc] initWithFrame:CGRectMake(10, 10, cardWidth - 20, 30)];
        previewBox.backgroundColor = [[UIColor systemGrayColor] colorWithAlphaComponent:0.1] ;
        previewBox.layer.cornerRadius = 4;
        
        // 根据不同模式添加不同的预览图标
        UIView *previewContent = [[UIView alloc] initWithFrame:CGRectMake(10, 10, cardWidth - 40, 10)];
        previewContent.backgroundColor = [[UIColor systemGrayColor] colorWithAlphaComponent:0.3];
        previewContent.layer.cornerRadius = 2;
        
        if (i == 0) { // 简洁模式
            previewContent.frame = CGRectMake(10, 10, cardWidth - 40, 10);
        } else if (i == 1) { // 详细模式
            previewContent.frame = CGRectMake(10, 5, cardWidth - 40, 20);
        } else { // 智能折叠
            previewContent.frame = CGRectMake(10, 5, cardWidth - 40, 15);
        }
        
        [previewBox addSubview:previewContent];
        [cardView addSubview:previewBox];
        
        // 标题
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, cardHeight - 30, cardWidth, 20)];
        label.text = titles[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = self.selectedDisplayMode == i ? [UIColor systemGreenColor] : [UIColor labelColor];
        [cardView addSubview:label];
        
        // 添加点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(displayModeCardTapped:)];
        [cardView addGestureRecognizer:tap];
        
        [scrollView addSubview:cardView];
    }
    
    // 设置滚动视图的内容大小
    scrollView.contentSize = CGSizeMake(startX * 2 + titles.count * (cardWidth + cardSpacing) - cardSpacing, 100);
    
    return containerView;
}

- (void)displayModeCardTapped:(UITapGestureRecognizer *)sender {
    NSInteger selectedIndex = sender.view.tag;
    if (self.selectedDisplayMode != selectedIndex) {
        self.selectedDisplayMode = selectedIndex;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return self.isFirstSwitchOn ? 1 : 0;
    } else {
        return (self.isFirstSwitchOn && self.isSecondSwitchOn) ? 1 : 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        static NSString *displayModeCellId = @"DisplayModeCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:displayModeCellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:displayModeCellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        // 移除所有子视图
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        // 添加显示模式视图
        UIView *displayModeView = [self createDisplayModeView];
        [cell.contentView addSubview:displayModeView];
        
        return cell;
    } else {
        static NSString *switchCellId = @"SwitchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:switchCellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:switchCellId];
        }
        
        // 创建防呆开关替代普通UISwitch
        ZLAntiShakeSwitch *antiShakeSwitch = [ZLAntiShakeSwitch switchWithIdentifier:[NSString stringWithFormat:@"message_switch_%ld", (long)indexPath.section]];
        antiShakeSwitch.antiShakeInterval = 1.0; // 1秒防呆间隔
        antiShakeSwitch.enableGlobalMutex = YES; // 启用全局互斥
        
        // 设置开关状态和回调
        if (indexPath.section == 0) {
            cell.textLabel.text = @"允许「短信」相关消息同步到眼镜";
            antiShakeSwitch.on = self.isFirstSwitchOn;
            
            __weak typeof(self) weakSelf = self;
            [antiShakeSwitch setValueChangedBlock:^(ZLAntiShakeSwitch *antiShakeSwitch, BOOL isOn) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if (strongSelf) {
                    [strongSelf handleFirstSwitchChanged:isOn];
                }
            }];
        } else {
            cell.textLabel.text = @"息屏显示";
            antiShakeSwitch.on = self.isSecondSwitchOn;
            
            __weak typeof(self) weakSelf = self;
            [antiShakeSwitch setValueChangedBlock:^(ZLAntiShakeSwitch *antiShakeSwitch, BOOL isOn) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if (strongSelf) {
                    [strongSelf handleSecondSwitchChanged:isOn];
                }
            }];
        }
        
        cell.accessoryView = antiShakeSwitch;
        
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 1 && self.isFirstSwitchOn) {
        return @"权限管理";
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 2 && self.isFirstSwitchOn && self.isSecondSwitchOn) {
        return @"收到长消息时，内容先折叠，在你「提控」后，展开全文";
    }
    return nil;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        return 140.0;
    }
    return 44.0;
}

#pragma mark - Actions

// 新的防呆开关事件处理方法
- (void)handleFirstSwitchChanged:(BOOL)isOn {
    self.isFirstSwitchOn = isOn;
    NSLog(@"短信同步开关状态变更为: %@", isOn ? @"开启" : @"关闭");
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 2)] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    // 可以在这里添加具体的业务逻辑
    if (isOn) {
        NSLog(@"已开启短信相关消息同步到眼镜功能");
    } else {
        NSLog(@"已关闭短信相关消息同步到眼镜功能");
    }
}

- (void)handleSecondSwitchChanged:(BOOL)isOn {
    self.isSecondSwitchOn = isOn;
    NSLog(@"息屏显示开关状态变更为: %@", isOn ? @"开启" : @"关闭");
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    // 可以在这里添加具体的业务逻辑
    if (isOn) {
        NSLog(@"已开启息屏显示功能");
    } else {
        NSLog(@"已关闭息屏显示功能");
    }
}

// 旧的事件处理方法保持兼容（如果有其他地方使用）
- (void)switchValueChanged:(UISwitch *)sender {
    // 这个方法现在已被防呆开关的回调取代
    NSLog(@"注意：switchValueChanged方法已被防呆开关回调取代");
}

- (void)resetAntiShake {
    // 重置所有开关的防呆状态
    [ZLAntiShakeSwitch resetAllAntiShakeStates];
    
    // 显示提示
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" 
                                                                   message:@"已重置所有开关的防呆状态，现在可以立即操作任意开关" 
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" 
                                                       style:UIAlertActionStyleDefault 
                                                     handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end